namespace utils{
    export class ByteArray{
        protected buff:ArrayBuffer;
        protected dataView:DataView;
        private _position:number = 0;
        constructor(buf?:ArrayBuffer){
            this.buff = buf?buf:new ArrayBuffer(128); //可以动态扩展内存，基本思路是：在每次写入的时候判断当前内存是否足够,,不够的重新设置
            this.dataView = new DataView(this.buff)
        }

        public writeInt16(val:number):void{
            this.dataView.setInt16(this._position,val,true);
            this._position += 2;
            console.log("this.dataView",this.dataView)
        }

        public writeInt32(val:number):void{
            this.dataView.setInt32(this._position,val,true);
            this._position += 4;
        }

        public writeUTF(str:string):void{
            let encoder:TextEncoder = new TextEncoder();
            
            let u8a:Uint8Array = new Uint8Array(encoder.encode(str))
            console.log("writeUTF u8a",u8a,"u8a.byteLength",u8a.byteLength);
            
            this.writeInt16(u8a.byteLength)
            for(let i:number = 0;i<u8a.byteLength;i++){
                this.dataView.setUint8(this._position,u8a[i]);
                this._position += 1;
            }
        }

        public readInt16():number{
            let val:number = this.dataView.getInt16(this._position,true);
            this._position+=2;
            return val;
        }
        public readInt32():number{
            let val:number = this.dataView.getInt32(this._position,true);
            this._position+=4;
            return val;
        }

        public readUTF():string{
            let len:number = this.readInt16()
            let buf:ArrayBuffer = this.dataView.buffer.slice(this._position,this._position+len);
            let u8a:Uint8Array = new Uint8Array(buf,0)
            let d:TextDecoder = new TextDecoder("utf-8")
            
            this._position += u8a.byteLength; 
            return d.decode(u8a);
        }

        public get position():number{
            return this._position;
        }
        public set position(value:number){
            this._position = value;
        }
    }
}